import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xindong/common/xindong_define.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/extension/extension_list.dart';
import 'package:xindong/utils/xindong_conversion_util.dart';
import 'package:xindong/widgets/dialog/xindong_base_alert.dart';
import 'package:xindong/widgets/video/xindong_common_video_player_layer.dart';
import 'package:xindong/widgets/video/xindong_common_video_player_full_screen_yemian.dart';
import 'package:video_player/video_player.dart';

/// 列表视频自动播放
class XinDongCommonVideoListCtr extends GetxController {
  static XinDongCommonVideoListCtr get to => Get.find();

  static double viewTop = statusBarHeight + kAppBarHeight;
  static double viewHeight = screenHeight - viewTop - kTabBarHeight - bottomBarHeight;
  final double linePositionMin = 100;
  final double linePositionMax = viewHeight - 200; // 这个看实际设置（动态高度一般有视频会超过200）
  late double linePosition = linePositionMin;

  // 正在播放的控制器
  VideoPlayerController? fullScreenVideoPlayerController;

  // 正在播放Key，数组一般只有1个元素，多列并排可能就有多个
  var videoPlayingKeys = RxList(<String>[]);

  // 显示的Item上下文
  final _videoKeyContextMap = <String, BuildContext>{};

  // 生成动态KEY
  String generateMomentKey({required dynamic did, bool isDetails = false, bool isSpace = false}) {
    if (isDetails) {
      return "moment_details_$did";
    }
    if (isSpace) {
      return "moment_space_$did";
    }
    return "moment_list_$did";
  }

  // 生成用户KEY
  String generateUserKey({required int uid}) {
    return "user_$uid";
  }

  // 添加上下文到数据
  void addContext({required String videoKey, required BuildContext context}) {
    _videoKeyContextMap[videoKey] = context;
  }

  // 移除上下文
  void removeContext({required String videoKey}) {
    if (_videoKeyContextMap.containsKey(videoKey)) {
      _videoKeyContextMap.remove(videoKey);
    }
  }

  /// 清除
  void clear() {
    try {
      if (fullScreenVideoPlayerController?.value.isInitialized == true && fullScreenVideoPlayerController?.value.isPlaying == true) {
        fullScreenVideoPlayerController?.pause();
        videoPlayingKeys.clear();
        update();
      }
    } catch (error) {
      mCatchPrint(error);
    }
  }

  /// 滚动监听
  void onScrollControllerListener({ScrollNotification? notification}) {
    if (notification != null) {
      final currentPixel = notification.metrics.pixels;
      final maxScrollExtent = notification.metrics.maxScrollExtent;
      onListenerScrollEnd(currentPixel, maxScrollExtent);
    }
  }

  /// 滚动监听（参数合适，可以跳过onScrollControllerListener直接使用）
  ///
  /// 微信朋友圈的方案是滚动结束的时候才播放视频
  void onListenerScrollEnd(double currentPixel, double maxScrollExtent) {
      // 计算播放基准线，屏幕列表中间偏上位置
      if (maxScrollExtent != 0) {
        linePosition = max(linePositionMin, min(viewHeight * currentPixel / (maxScrollExtent + 300), linePositionMax));
      } else {
        linePosition = viewHeight / 2;
      }
      // 匹配处于基准线的上下文所属的key
      _matchVideoKeys();
  }

  /// 匹配处于基准线的上下文所属的key
  void _matchVideoKeys() {
    List<String> tempKeys = [];
    try {
      for (String key in _videoKeyContextMap.keys) {
        BuildContext context = _videoKeyContextMap[key]!;
        double topY = XinDongConversionUtil.xindong_getWidgetOffset(context, offsetY: -viewTop).dy;
        double bottomY = topY + XinDongConversionUtil.xindong_getWidgetSize(context).height;

        // 位置在坐标线上就可以播放
        if (topY < linePosition && bottomY > linePosition) {
          tempKeys.add(key);
        }
      }
    } catch (error) {
      mCatchPrint(error);
    }

    // 当id改变时，通知播放和暂停
    if (!videoPlayingKeys.isEqual(tempKeys)) {
      videoPlayingKeys.clear();
      videoPlayingKeys.addAll(tempKeys);
      update();
    }
  }

  /// 退出全屏事件
  void xindong_onExitFullScreen(BuildContext context) {
    // 静音
    fullScreenVideoPlayerController?.setVolume(0);
    // 移除监听
    fullScreenVideoPlayerController?.removeListener(() {});
    // 退出全部
    Navigator.pop(context);
  }

  /// 全屏事件
  void xindong_onFullScreen({required String videoKey, required VideoPlayerController playerController}) async {
    if (!videoPlayingKeys.contains(videoKey)) {
      // 赋值播放器
      fullScreenVideoPlayerController = playerController;
      fullScreenVideoPlayerController?.play();
      update();
    } else {
      // 赋值播放器
      fullScreenVideoPlayerController = playerController;
    }
    // 开放声音
    fullScreenVideoPlayerController?.setVolume(1);
    // 全屏弹出
    await showAlertDialog(alert: XinDongCommonVideoPlayerFullScreenYeMian(videoHeroKey: videoKey));
    // 延时，避免过早触发pause()造成setState异常
    Future.delayed(const Duration(milliseconds: 300)).whenComplete(() {
      update();
    });
  }
}

/// 视图
extension XinDongCommonListVideoView on XinDongCommonVideoListCtr {
  /// 正常播放视图
  ///
  /// videoKey 视频Key
  /// cover 封面地址（不传时为透明的SizedBox()）
  /// playerController 视频播放控制器
  Widget normalPlayerView({required String videoKey, required String? cover, required VideoPlayerController playerController}) {
    try {
      if (videoPlayingKeys.contains(videoKey)) {
        if (playerController.value.isInitialized && !playerController.value.isPlaying) {
          playerController.play();
        }
      } else {
        playerController.pause();
      }
    } catch (error) {
      mCatchPrint(error);
    }
    return XinDongCommonVideoPlayerSmallLayer(videoPlayerController: playerController, videoKey: videoKey, cover: cover);
  }

  /// 全屏播放视图
  Widget fullScreenPlayerView(String videoHeroKey) {
    return Hero(
      tag: videoHeroKey,
      child: XinDongCommonVideoPlayerBigLayer(fullScreenVideoPlayerController),
    );
  }
}
